package router

import (
	"encoding/json"
	"fmt"
	"image-pull/tcpServer"
	"net"
	"net/http"
	"sync"
	"time"

	"github.com/gin-gonic/gin"
)

type dockerInfo struct {
	UserName  string `json:"userName"`
	Password  string `json:"passWord"`
	ImageName string `json:"imageName"`
}

type imageInfoStruct struct {
	DockerPullImage []dockerInfo `json:"dockerPullImage"`
}

func sendImageInfo(ctx *gin.Context) {
	var (
		imageInfo imageInfoStruct
		err       error
	)
	if err = ctx.BindJSON(&imageInfo); err != nil {
		fmt.Println(err)
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	// 查询匹配的客户端列表
	clientList, ok := tcpServer.List()
	if !ok {
		fmt.Println("没有查询到对应的client连接地址")
		ctx.JSON(http.StatusNotFound, gin.H{"message": "没有查询到对应的client连接地址"})
		time.Sleep(time.Second)
		return
	}
	var wg sync.WaitGroup
	for _, conn := range clientList {
		b, _ := json.Marshal(imageInfo.DockerPullImage)

		wg.Add(1)
		go func(conn net.Conn) {
			defer wg.Done()
			tcpServer.Send(conn, string(b))
		}(conn)
	}

	ctx.JSON(http.StatusOK, "请求成功")
}

// 获取已注册节点信息
func getRegisteredList(ctx *gin.Context) {
	val, ok := tcpServer.List()
	if !ok {
		ctx.JSON(http.StatusNotFound, gin.H{"message": "没有查询到对应的client连接地址"})
		return
	}
	clientCount := len(val)
	b, err := json.Marshal(val)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "JSON encoding failed"})
		return
	}
	fmt.Printf("查询匹配到的客户端共：%d个，详情：%s\n", clientCount, string(b))
	// 返回查询到的客户端列表
	ctx.JSON(http.StatusOK, gin.H{"clients": string(b)})
}
